/***************************************************************************
 *  Filename: parsaxremotecontrol.cpp
 *  Class: ParsaxRemoteControl
 *
 *  Copyright 2012  Xander van Kooten
 *  <xandervk@gmail.com>
 *
 *  Copyright 2012  Mario Henrique Voorsluys
 *  <forcaeluz@gmail.com>
 *
 ****************************************************************************/

/*
 *
 * This file is part of Parsax-Remote-Controller.
 *
 *    Parsax-Remote-Controller is free software: you can redistribute it
 *    and/or modify it under the terms of the GNU General Public License
 *    as published by the Free Software Foundation, either version 3 of the
 *    License, or (at your option) any later version.
 *
 *    Parsax-Remote-Controller is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with Parsax-Remote-Controller.
 *    If not, see <http://www.gnu.org/licenses/>.
 */

#include "parsaxremotecontrol.h"
#include "ui_parsaxremotecontrol.h"
#include "processmodel.h"
#include "remotecomputer.h"

ParsaxRemoteControl::ParsaxRemoteControl(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ParsaxRemoteControl)
{
    qDebug() << "[ParsaxRemoteControl] Parsax Controller Created";
    ui->setupUi(this);
    processes = new ProcessModel(true, this);
    ui->tableView->setModel(processes);
    ui->tableView->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setResizeMode(2, QHeaderView::Stretch);
    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);
    loadSettings();
}

ParsaxRemoteControl::~ParsaxRemoteControl()
{
    saveSettings();
    delete ui;
}

void ParsaxRemoteControl::loadSettings(){
    QSettings settings("CCC-Buienradar", "Parsax Master");
    int size = settings.beginReadArray("slaves");
    for (int i = 0; i < size; i++){
        settings.setArrayIndex(i);
        QString name = settings.value("name").toString();
        QString addres = settings.value("address").toString();
        int port = settings.value("port").toInt();

        ComputerWidget *newCmp = new ComputerWidget(0, this);
        newCmp->setName(name);
        newCmp->setAddress(addres);
        newCmp->setPort(port);
        addComputer(newCmp);
        int sizep = settings.beginReadArray("processes");
        for (int j = 0; j < sizep; j++){
            settings.setArrayIndex(j);
            ProcessGUI *newPrcs = new ProcessGUI(0, newCmp);
            newPrcs->setId(settings.value("id").toString());
            newPrcs->setPc(name);
            newPrcs->setProgram(settings.value("name").toString());
            newPrcs->setParameters(settings.value("param").toStringList());
            newCmp->addProccess(newPrcs);
            processes->addProcess(newPrcs->getProcess());
            ui->tableView->resizeRowsToContents();
            ui->tableView->resizeColumnsToContents();
        }
        settings.endArray();
    }
    settings.endArray();
}

void ParsaxRemoteControl::saveSettings(){
    QSettings settings("CCC-Buienradar", "Parsax Master");
    int size = computers.size();
    settings.beginWriteArray("slaves");
    for (int i = 0; i < size; i++){
        settings.setArrayIndex(i);
        ComputerWidget *newCmp = computers.at(i);
        settings.setValue("name", newCmp->getName());
        settings.setValue("address", newCmp->getAddress());
        settings.setValue("port", newCmp->getPort());
        QList<ProcessGUI*> procList = newCmp->getProcess();
        int sizep = procList.size();
        settings.beginWriteArray("processes");
        for (int j = 0; j < sizep; j++){
            settings.setArrayIndex(j);
            ProcessGUI *newPrcs = procList.at(j);
            settings.setValue("id", newPrcs->getId());
            settings.setValue("name", newPrcs->getProgram());
            settings.setValue("param", newPrcs->getParameters());
        }
        settings.endArray();
    }
    settings.endArray();
}

void ParsaxRemoteControl::addComputer(){
    qDebug() << "[ParsaxRemoteControl] Adding empty computer";
    QString tmpComputerName = "Computer " + QString::number(computers.size());
    addComputer(tmpComputerName, "127.0.0.1", 33300);
}

void ParsaxRemoteControl::addComputer(ComputerWidget *cmpWidget){
    qDebug() << "[ParsaxRemoteControl] Adding computer with object pointer";
    cmpWidget->initialize();
    connect(cmpWidget, SIGNAL(processAdded(ProcessGUI*)), SLOT(processAdded(ProcessGUI*)));
    connect(cmpWidget, SIGNAL(nameChanged(ComputerWidget*,QString)), SLOT(computerRenamed(ComputerWidget*,QString)));
    connect(cmpWidget, SIGNAL(processRemoved(ProcessGUI*)), SLOT(processRemoved(ProcessGUI*)));

    computers.append(cmpWidget);
    ui->computerTabs->addTab(cmpWidget, cmpWidget->getName());
}

void ParsaxRemoteControl::addComputer(QString name, QString address, int port){
    qDebug() << "[ParsaxRemoteControl] Adding computer with arguments";
    ComputerWidget *newcomputer = new ComputerWidget(0, this);
    newcomputer->setName(name);
    newcomputer->setAddress(address);
    newcomputer->setPort(port);
    addComputer(newcomputer);
}

void ParsaxRemoteControl::processAdded(ProcessGUI *prcs){

    processes->addProcess(prcs->getProcess());
    ui->tableView->resizeRowsToContents();
}

void ParsaxRemoteControl::on_actionExit_triggered()
{
    foreach(ComputerWidget *tmp, computers){
        tmp->closeConnection();
    }

    this->close();
}

void ParsaxRemoteControl::on_actionAdd_Computer_triggered()
{
    qDebug() << "[ParsaxRemoteControl] Add Computer Action triggered";
    addComputer();
}

void ParsaxRemoteControl::computerRenamed(ComputerWidget * pc, QString name){
    int index = ui->computerTabs->indexOf(pc);
    ui->computerTabs->setTabText(index, name);
}

void ParsaxRemoteControl::processRemoved(ProcessGUI *prcs){
    processes->removeProcess(prcs->getProcess());
}

void ParsaxRemoteControl::on_tableView_customContextMenuRequested(const QPoint &pos)
{
    qDebug() << "[ParsaxRemoteControl] Menu requested";
    QModelIndex index = ui->tableView->indexAt(pos);
    RemoteProcess *tmpPrcs = (RemoteProcess*)ui->tableView->model()->data(index, 33).value<void*>();
    if(tmpPrcs==0){
        qDebug() << "[ComputerWidget] Something went wrong when parsing pointers";
        return;
    }
    RemoteComputer *tmpCmp;
    foreach(ComputerWidget *cmp, computers){
        if(cmp->getName()==tmpPrcs->getPc()){
            tmpCmp = cmp->getComputer();
            break;
        }
    }

    QMenu tmp("Remote Process");
    if(tmpPrcs->getStatus()=="notrunning"){
        tmp.addAction("Start Process", tmpPrcs, SLOT(startProcess()));
    }else if(tmpPrcs->getStatus()=="running"){
        tmp.addAction("Stop Process", tmpPrcs, SLOT(stopProcess()));
    }else if(tmpPrcs->getStatus()=="disconnected"){
        tmp.addAction("Connect to Slave", tmpCmp, SLOT(connectToSlave()));
    }
    tmp.exec(cursor().pos());
}
